package com.readword.util;


import java.io.FileOutputStream;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.html2pdf.resolver.font.DefaultFontProvider;
import com.itextpdf.io.IOException;
import com.itextpdf.io.font.otf.GlyphLine;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.IBlockElement;
import com.itextpdf.layout.element.IElement;
import com.itextpdf.layout.property.Property;
import com.itextpdf.layout.splitting.DefaultSplitCharacters;

/**
* @ClassName: ItextPdfUtil
* @Description: html转pdf
* @author 码农小鹿
* @date 2024年1月13日 上午3:32:07
*
 */
public class ItextPdfUtil {
	private final static Logger logger = LoggerFactory.getLogger(TextParserUtil.class);

    public static void htmlToPdf(String htmlStr, String pdfName){
        Document document = null;
        try {
            PdfDocument pd = new PdfDocument(new PdfWriter(new FileOutputStream(Cons.FILE.SAVEFOLDER + pdfName)));
            document = new Document(pd, PageSize.A4);
            document.setProperty(Property.SPLIT_CHARACTERS, new DefaultSplitCharacters() {
                @Override
                public boolean isSplitCharacter(GlyphLine text, int glyphPos) {
                    //解决word-break: break-all;不兼容的问题，解决纯英文或数字不自动换行的问题
                    return true;
                }
            });
            DefaultFontProvider defaultFontProvider = new DefaultFontProvider(false, false, false);
            //字体路径
            defaultFontProvider.addFont("static/fonts/simsun.ttf");
            ConverterProperties c = new ConverterProperties();
            c.setCharset("utf-8");
            c.setFontProvider(defaultFontProvider);
            List<IElement> list = HtmlConverter.convertToElements(htmlStr, c);
            for (IElement ie : list) {
                document.add((IBlockElement) ie);
            }
        } catch (IOException e) {
        	logger.error("HtmlToPDF 转换pdf失败....",e);
            throw  new RuntimeException("HtmlToPDF 转换pdf失败....",e);
        } catch (Exception e) {
        	logger.error("HtmlToPDF 转换pdf失败....", e);
            throw  new RuntimeException("HtmlToPDF 转换pdf失败....",e);
        } finally {
            if (document != null) {
                try {
                    document.close();
                } catch (Exception e) {
                	logger.error("document关闭异常...",e);
                }
            }
        }
    }
}

